package com.sp2p.action.front;

import com.shove.Convert;
import com.shove.data.DataException;
import com.shove.util.ServletUtils;
import com.shove.web.util.ExcelUtils;
import com.shove.web.util.JSONUtils;
import com.sp2p.constants.IConstants;
import com.sp2p.entity.Admin;
import com.sp2p.entity.User;
import com.sp2p.service.*;
import com.sp2p.service.admin.AdminService;
import com.sp2p.service.admin.FundManagementService;
import com.sp2p.service.admin.RechargebankService;
import com.sp2p.service.admin.UserManageServic;
import com.sp2p.util.CertNoUtil;
import com.sp2p.util.DateUtil;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.io.StringReader;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.sp2p.system.interceptor.FrontUserSeesionInterceptor.StringFilter;

public class RechargeAction extends BaseFrontAction {

	public static Log log = LogFactory.getLog(FrontMyFinanceAction.class);
	private static final long serialVersionUID = 1L;
	private RechargeService rechargeService;
	private HomeInfoSettingService homeInfoSettingService;
	private UserService userService;
	private FinanceService financeService;
	private AdminService adminService;
	private RechargebankService rechargebankService;
	private FundManagementService fundManagementService;
	private UserManageServic userManageServic;
	private BeVipService beVipService;
	private String transAmt;
	private String bankCode;
	
	public String getTransAmt() {
		return transAmt;
	}
	public void setTransAmt(String transAmt) {
		this.transAmt = transAmt;
	}
	public String getBankCode() {
		return bankCode;
	}
	public void setBankCode(String bankCode) {
		this.bankCode = bankCode;
	}

	public FundManagementService getFundManagementService() {
		return fundManagementService;
	}


	private List<Map<String, Object>> potypeList;
	private List<Map<String, Object>> banksList;

	public void setFundManagementService(
			FundManagementService fundManagementService) {
		this.fundManagementService = fundManagementService;
	}
	public void setBeVipService(BeVipService beVipService) {
		this.beVipService = beVipService;
	}
	
	/**
	 * 查询交易记录
	 * 
	 * @return
	 * @throws Exception
	 */
	public String queryFundrecordInit() throws Exception {
		return SUCCESS;
	}
	
	public void queryFundrecordList() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		
		int tradeType = Convert.strToInt(paramMap.get("tradeType"), 0);//交易类型:0 全部,1 充值,2 提现,3 投资,4 还款,5 其他
		int timeType = Convert.strToInt(paramMap.get("timeType"), 0);//时间类型：0 最近7天,1 1个月,2 2个月,3 3个月
		String startTime = Convert.strToStr(paramMap.get("startTime"), null);
		String endTime = Convert.strToStr(paramMap.get("endTime"), null);
		int currentPage = Convert.strToInt(paramMap.get("currentPage"), 1);
		int pageSize = Convert.strToInt(paramMap.get("pageSize"), 10);
		
		pageBean.setPageNum(currentPage);
		pageBean.setPageSize(pageSize);
		
		rechargeService.queryFundrecordList(pageBean, userId, startTime,
				endTime, tradeType, timeType);
		
		JSONObject obj = new JSONObject();
		if(pageBean.getTotalNum() > 0){
			obj.put("voList", JSONUtils.toJSONArray(pageBean.getPage()));
			obj.put("currentPage", currentPage);
			obj.put("pageCount", pageBean.getTotalPageNum());
			JSONUtils.printObject(obj);
		}
		
	}
	
	/**
	 * 导出交易记录
	 * 
	 * @return
	 */
	public String exportFundrecordList() {
		pageBean.pageNum = 1;
		pageBean.setPageSize(IConstants.EXCEL_MAX);

		try {
			User user = (User) session().getAttribute(IConstants.SESSION_USER);
			Long userId = user.getId();// 获得用户编号

			int tradeType = Convert.strToInt(request().getParameter("tradeType"), 0);//交易类型:0 全部,1 充值,2 提现,3 投资,4 还款,5 其他
			int timeType = Convert.strToInt(request().getParameter("timeType"), 0);//时间类型：0 最近7天,1 1个月,2 2个月,3 3个月
			String startTime = Convert.strToStr(request().getParameter("startTime"), null);
			String endTime = Convert.strToStr(request().getParameter("endTime"), null);
			
			rechargeService.queryFundrecordList(pageBean, userId, startTime,
					endTime, tradeType, timeType);
			
			if (pageBean.getPage() == null) {
				getOut().print("<script>alert(' 导出记录条数不能为空! ');window.history.go(-1);</script>");
				return null;
			}
			if (pageBean.getPage().size() > IConstants.EXCEL_MAX) {
				getOut().print("<script>alert(' 导出记录条数不能大于50000条 ');window.history.go(-1);</script>");
				return null;
			}
			fundManagementService.changeFigure(pageBean);
			HSSFWorkbook wb = ExcelUtils.exportExcel("资金记录",
					pageBean.getPage(), new String[] { "时间", "交易类型", "摘要",
							"金额", "可用余额"},
					new String[] { "recordTime", "fundMode", "stripTagsRemarks",
							"handleSum", "usableSum" });
			this.export(wb, new Date().getTime() + ".xls");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (DataException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 充值提现
	 * 
	 * @return
	 */
	public String rechargeWithdrawPage() throws Exception{
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Map<String, String> userMap = userService.queryUserById(user.getId());
		request().setAttribute("userMap", userMap);
		
		//重写用户session中的可用余额
		user.setUsableSum(Convert.strToDouble(userMap.get("usableSum"),0.00));
		session().setAttribute("user", user);
		
		return SUCCESS;
	}

	public String rechargeInit() throws Exception {
		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		
		//判断用户是否已经实名认证
		Map<String, String> materialsauthMap = userService.isCheckIDCard(user.getId());
		if(materialsauthMap == null || materialsauthMap.size() == 0 || !(materialsauthMap.get("auditStatus").equals("3"))){
			request().setAttribute("userMaterialsauthStats", 0);
		}else{
			request().setAttribute("userMaterialsauthStats", materialsauthMap.get("auditStatus"));
		}
		
		return SUCCESS;
	}
	
	
	/**
	 * 提现信息加载
	 * 
	 * @return
	 * @throws Exception
	 */
	public String withdrawLoad() throws Exception {
		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		
		Map<String, String>  withdrawNumMap = rechargeService.querywithdrawNum(userId);//已提现次数
		request().setAttribute("withdrawNum", withdrawNumMap.get("withdrawNum"));
		
		Map<String, String>  freeNumMap = rechargeService.queryNum();//提现免费次数
		request().setAttribute("freeNum", freeNumMap.get("freeNum"));
		
		Map<String, String>  FeeRateMap = rechargeService.queryFeeRate();//提现费率
		request().setAttribute("FeeRate", FeeRateMap.get("FeeRate"));
		//可用余额
		String[] vals = moneyVal(userId);
		request().setAttribute("usableSum", vals[1]);
		
		List<Map<String, Object>> banks = homeInfoSettingService.querySuccessBankInfoList(userId);
		request().setAttribute("banks", banks);
		return SUCCESS;
	}
	
	public String withdraw_step2() throws Exception {
		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		
		Map<String, String>  withdrawNumMap = rechargeService.querywithdrawNum(userId);//提现次数
		request().setAttribute("withdrawNum", withdrawNumMap.get("withdrawNum"));
		
		Map<String, String>  freeNumMap = rechargeService.queryNum();//提现免费次数
		request().setAttribute("freeNum", freeNumMap.get("freeNum"));
		
		Map<String, String>  FeeRateMap = rechargeService.queryFeeRate();//提现费率
		request().setAttribute("FeeRate", FeeRateMap.get("FeeRate"));
		//可用余额
		String[] vals = moneyVal(userId);
		request().setAttribute("usableSum", vals[1]);
		
		String bankId = Convert.strToStr(request("bankId"), "-1");
		Map<String, String> bank = homeInfoSettingService.queryBankInfoById(bankId);//银行卡
		request().setAttribute("bank", bank);
		
		//预期到账日期
		Map<String, String>  expectedDate = rechargeService.queryWithdrawExpectedDate();
		request().setAttribute("expectedDate", expectedDate.get("expectedDate"));
		
		return SUCCESS;
	}
	
	public String withdraw_step3() throws Exception {
		//预期到账日期
		Map<String, String>  expectedDate = rechargeService.queryWithdrawExpectedDate();
		request().setAttribute("expectedDate", expectedDate.get("expectedDate"));
		return SUCCESS;
	}

	public void addWithdraw() throws Exception {
		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		JSONObject obj = new JSONObject();
		// ip地址
		String ipAddress = ServletUtils.getRemortIp();
		String dealpwd = Convert.strToStr(request("payPassword"), "");
		String withdrawMoney = request("withdrawMoney");
		double withdrawMoneyD = Convert.strToDouble(withdrawMoney, 0);
		String bankId = request("bankId");
		long bankIdL = Convert.strToLong(bankId, -1);
		String type = "";
		if (bankIdL < 0){
			obj.put("result", "无效的银行卡");
			JSONUtils.printObject(obj);
			return;
		}
		
		if ("1".equals(IConstants.ENABLED_PASS)) {
			dealpwd = com.shove.security.Encrypt.MD5(dealpwd.trim());
		} else {
			dealpwd = com.shove.security.Encrypt.MD5(dealpwd.trim() + IConstants.PASS_KEY);
		}
		Map<String, String> retMap = rechargeService.withdrawApply(userId,withdrawMoneyD, dealpwd, bankIdL, type, ipAddress);
		long retVal = -1;
		retVal = Convert.strToLong(retMap.get("ret") + "", -1);
		if (retVal <= 0) {
			obj.put("result", retMap.get("ret_desc"));
		} else {
			obj.put("result", "success");
		}
		JSONUtils.printObject(obj);
	}
	
	
	
	
	
	
	
//v1.0-------------------------------------------------------------------------------------------------------------------------	
	/**
	 * 加载提现记录信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String queryWithdrawList() throws Exception {
		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);

		Long userId = user.getId();// 获得用户编号

		pageBean.setPageSize(IConstants.PAGE_SIZE_6);
		try {
			rechargeService.queryWithdrawList(pageBean, userId, 0, null);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
		return SUCCESS;
	}

	public String addRechargeoutline() throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String, String> recharMap = new HashMap<String, String>();
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		long userid = user.getId();
		String rechargeMoneystr = paramMap.get("money") + "";
		String realname = paramMap.get("realname");
		Pattern pattern = Pattern.compile("^(-)?\\d+(\\.\\d+)?$");
		Matcher m = pattern.matcher(rechargeMoneystr);
		if (StringUtils.isBlank(realname)
				|| !realname.equals(user.getRealName())) {
			jsonMap.put("msg", " 请输入正确的真实姓名！");
			JSONUtils.printObject(jsonMap);
			return null;
		}
		if (!m.matches()) {
			jsonMap.put("msg", " 请输入正确的充值金额！");
			JSONUtils.printObject(jsonMap);
			return null;
		}
		double rechargeMoney = Convert.strToDouble(rechargeMoneystr, 0);
		if (rechargeMoney <= 0) {
			jsonMap.put("msg", "充值金额不能小于零！");
			JSONUtils.printObject(jsonMap);
			return null;
		}
		String bankName = paramMap.get("bankName");
		if (StringUtils.isBlank(bankName)) {
			jsonMap.put("msg", "请选定充值帐户！");
			JSONUtils.printObject(jsonMap);
			return null;
		}
		String rechargeNumber = paramMap.get("rechargeNumber") + "";
		String remark = paramMap.get("remark") + "";
		if (StringUtils.isBlank(rechargeNumber)) {
			jsonMap.put("msg", " 交易编号不能为空！");
			JSONUtils.printObject(jsonMap);
			return null;
		}
		if (StringUtils.isBlank(remark)) {
			jsonMap.put("msg", "线下充值备注不能为空！");
			JSONUtils.printObject(jsonMap);
			return null;
		}
		recharMap.put("rechargeMoney", rechargeMoney + "");
		recharMap.put("userId", userid + "");
		SimpleDateFormat df = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
		recharMap.put("rechargeTime", df.format(new Date()) + "");
		recharMap.put("rechargeType", 4 + "");
		recharMap.put("result", 3 + "");// 3为审核中
		recharMap.put("rechargeNumber", rechargeNumber);
		recharMap.put("remark", remark);
		recharMap.put("bankName", bankName);
		long result = -1;
		result = rechargeService.addRechargeoutline(recharMap);

		if (result < 0) {
			jsonMap.put("msg", "提交失败");
			JSONUtils.printObject(jsonMap);
			return null;
		}

		jsonMap.put("msg", "提交成功");
		JSONUtils.printObject(jsonMap);
		return null;
	}

	

	public static String getNeedTime(Date currDate) {
		try {
			String currDateStr = DateUtil.YYYY_MM_DD.format(currDate);
			currDate = DateUtil.YYYY_MM_DD.parse(currDateStr);
			long currTime = currDate.parse(currDate.toString());
			long delTime = IConstants.WITHDRAW_TIME * 24 * 60 * 60 * 1000;
			long needTime = currTime - delTime;
			Date needDate = new Date();
			needDate.setTime(needTime);
			String needDateStr = DateUtil.YYYY_MM_DD.format(needDate);
			return needDateStr;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 删除提现记录
	 * 
	 * @return
	 * @throws Exception
	 */
	public String deleteWithdraw() throws Exception {
		JSONObject obj = new JSONObject();
		long wid = Convert.strToLong(paramMap.get("wId"), -1);
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		try {
			// 删除提现记录
			Map<String, String> resultMap = rechargeService.deleteWithdraw(
					userId, wid);
			long result = Convert.strToLong(resultMap.get("ret") + "", -1);
			if (result <= 0) {
				obj.put("msg", resultMap.get("ret_desc") + "");
				JSONUtils.printObject(obj);
				return null;
			} else {
				obj.put("msg", "1");
				JSONUtils.printObject(obj);
				return null;
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
	}

	
	private String[] fundVal(long userId) throws Exception {
		String[] val = new String[3];
		for (int i = 0; i < val.length; i++) {
			val[i] = "0";
		}
		try {
			Map<String, String> map = rechargeService.queryFund(userId);
			if (map != null) {
				double usableSum = Convert.strToDouble(map.get("usableSum"), 0);
				double freezeSum = Convert.strToDouble(map.get("freezeSum"), 0);
				double dueinSum = Convert.strToDouble(map.get("forPI"), 0);
				double handleSum = usableSum + freezeSum + dueinSum;
				val[0] = String.format("%.2f", handleSum);
				val[1] = String.format("%.2f", usableSum);
				val[2] = String.format("%.2f", freezeSum);
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
		return val;
	}

	public String[] moneyVal(long userId) throws Exception {
		String[] val = new String[3];
		for (int i = 0; i < val.length; i++) {
			val[i] = "0";
		}
		try {
			Map<String, String> map = userService.queryUserById(userId);
			if (map != null) {
				double usableSum = Convert.strToDouble(map.get("usableSum"), 0);
				double freezeSum = Convert.strToDouble(map.get("freezeSum"), 0);
				double handleSum = usableSum + freezeSum;
				val[0] = String.format("%.2f", handleSum);// df.format(handleSum);
				val[1] = String.format("%.2f", usableSum);// df.format(usableSum);
				val[2] = String.format("%.2f", freezeSum);// df.format(freezeSum);
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
		return val;
	}

	// 根据日期取得星期几
	public static String getWeek(Date date) {
		String[] weeks = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (week_index < 0) {
			week_index = 0;
		}
		return weeks[week_index];
	}

	// 一周前的日期
	public static String lastWeek() {
		Date date = new Date();
		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(date));
		int day = Integer.parseInt(new SimpleDateFormat("dd").format(date)) - 6;

		if (day < 1) {
			month -= 1;
			if (month == 0) {
				year -= 1;
				month = 12;
			}
			if (month == 4 || month == 6 || month == 9 || month == 11) {
				day = 30 + day;
			} else if (month == 1 || month == 3 || month == 5 || month == 7
					|| month == 8 || month == 10 || month == 12) {
				day = 31 + day;
			} else if (month == 2) {
				if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
					day = 29 + day;
				else
					day = 28 + day;
			}
		}
		String y = year + "";
		String m = "";
		String d = "";
		if (month < 10)
			m = "0" + month;
		else
			m = month + "";
		if (day < 10)
			d = "0" + day;
		else
			d = day + "";
		return y + "-" + m + "-" + d;
	}

	// 获得一月前的日期
	public String lastMonth() {
		Date date = new Date();

		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(date)) - 1;
		int day = Integer.parseInt(new SimpleDateFormat("dd").format(date));
		if (month == 0) {
			year -= 1;
			month = 12;
		} else if (day > 28) {
			if (month == 2) {
				if (year == 0 || (year % 4 == 0 && year != 0)) {
					day = 29;
				} else
					day = 28;
			} else if ((month == 4 || month == 6 || month == 9 || month == 11)
					&& day == 31) {
				day = 30;
			}
		}
		String y = year + "";
		String m = "";
		String d = "";
		if (month < 10)
			m = "0" + month;
		else
			m = month + "";
		if (day < 10)
			d = "0" + day;
		else
			d = day + "";

		return y + "-" + m + "-" + d;
	}



	/**
	 * 充值记录
	 * 
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */

	public String queryRechargeInfo() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		List<Map<String, Object>> lists = null;
		int type = -1, status = -1;
		try {

			pageBean.setPageSize(IConstants.PAGE_SIZE_6);

			rechargeService.queryRechargeInfo(pageBean, userId);
			lists = pageBean.getPage();
			if (lists != null) {
				for (Map<String, Object> map : lists) {
					map.put("userId", user.getUserName());
					type = Convert.strToInt(map.get("rechargeType").toString(),
							-1);
					status = Convert.strToInt(map.get("result").toString(), -1);
					if (status == IConstants.RECHARGE_SUCCESS) {
						map.put("status", IConstants.RECHARGE_SUCCESS_STR);
					} else {
						map.put("status", IConstants.RECHARGE_CHECKING_STR);
					}
				}
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
		return SUCCESS;
	}

	/**
	 * 发送手机验证码
	 * 
	 * @return
	 */
	public String sendPhoneCode() {
		Random rand = new Random();
		int num = rand.nextInt(9999);
		while (num < 1000) {
			num = rand.nextInt(9999);
		}
		System.out.println("num====>" + num);
		String type = request("type");
		session().setAttribute(type + "_phoneCode", num);
		try {
			JSONUtils.printStr(num + "");
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 线下充值审核
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updateRechargeDetailStatusById() throws Exception {

		String award = paramMap.get("award");

		if (StringUtils.isBlank(award)) {
			award = "";
		} else {
			Pattern pattern = Pattern.compile("^(-)?\\d+(\\.\\d+)?$");
			Matcher m = pattern.matcher(award);
			if (!m.matches()) {
				this.addFieldError("paramMap.allerror", "输入奖励比例错误");
				return "input";
			}
		}
		long id = Convert.strToLong(paramMap.get("id"), -1);
		long userid = Convert.strToLong(paramMap.get("userId"), -1);
		if (id == -1) {
			this.addFieldError("paramMap.allerror", "审核失败");
			return "input";
		}
		if (userid == -1) {
			this.addFieldError("paramMap.allerror", "审核失败");
			return "input";
		}
		String typeStr = paramMap.get("type");
		long type = -1;
		if (typeStr.equals("a")) {// 审核成功
			type = 1;
		} else if (typeStr.equals("b")) {
			type = 0;
		} else {
			this.addFieldError("paramMap.allerror", "审核失败");
			return "input";
		}
		double rechargeMoney = Convert.strToDouble(paramMap
				.get("rechargeMoney")
				+ "", 0);
		if (rechargeMoney == 0) {
			this.addFieldError("paramMap.allerror", "审核失败");
			return "input";
		}
		long result = rechargeService.updateRechargeDetailStatusById(id,
				userid, type, rechargeMoney, award);
		Admin admin = (Admin) session().getAttribute(IConstants.SESSION_ADMIN);
		operationLogService.addOperationLog("t_recharge_detail", admin
				.getUserName(), IConstants.UPDATE, admin.getLastIP(),
				rechargeMoney, "线下审核", 2);
		if (result <= 0) {
			getOut()
					.print(
							"<script>alert('审核失败');window.location.href='queryxxRechargeInit.do';</script>");
			return null;
		}
		return SUCCESS;
	}
	
	public String checkUserIDCard() throws Exception {
		Pattern p = Pattern.compile("[a-zA-z]");	//是否包含字母

		response().setContentType("text/html");
		response().setCharacterEncoding("utf-8");
		request().setCharacterEncoding("utf-8");
		response().setContentType("text/html; charset=utf-8");
		String realName = StringFilter(Convert.strToStr(paramMap.get("realName"), null));
		String cardId = StringFilter(Convert.strToStr(paramMap.get("cardId"), null));

		if(p.matcher(realName).find() || isSpecialChar(realName))	//判断姓名是否包含字母或特殊字符
		{
			JSONUtils.printStr("40004");//返回用户已经认证
		}

		//先查看身份证号码有没有被注册
		Map<String, String> idNoMap = beVipService.queryIDCard(cardId);
		Map<String, String> realNameMap = beVipService.queryRealName(realName);
		
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Long userId = user.getId();// 获得用户编号
		
		if (idNoMap != null && !idNoMap.isEmpty()) {
			JSONUtils.printStr("4");//返回用户已经认证 
			
		}/*else if ( realNameMap != null && !realNameMap.isEmpty()){ //用户姓名已存在，送国政通认证
			//ws访问地址
			String url =GbossConfig.gboss_url;//"http://gboss.id5.cn/services/QueryValidatorServices?wsdl";
			String userName = GbossConfig.gboss_userName;//"yongtaijiekou";//用户名
			String password = GbossConfig.gboss_password;//"yongtaijiekou_671HeP))";//密码
			String datasource = GbossConfig.gboss_datasource;//"1A020201";//数据类型
			//单条
			String param = realName+","+cardId;//输入参数 
			System.out.println("未加密----用户名 -------"+userName);
			System.out.println("未加密----密码 -------"+password);
			System.out.println("未加密----数据类型 -------"+datasource);
			System.out.println("未加密----输入参数 -------"+param);
			System.out.println();
			String result = "";
			System.out.println("加密用户名---------"+encode("12345678", userName.getBytes("GB18030")));
			System.out.println("加密密码---------"+encode("12345678", password.getBytes("GB18030")));
			System.out.println("加密认证数据类型---------"+encode("12345678", datasource.getBytes("GB18030")));
			System.out.println("加密认证输入参数 （姓名,身份证号）---------"+encode("12345678", param.getBytes("GB18030")));
			Service service = new Service();
			Call call = (Call) service.createCall();
			try {
				call.setTargetEndpointAddress(url);
				call.setOperationName(new QName(url, "querySingle"));
				System.setProperty("javax.net.ssl.trustStore",
						"CheckID.keystore");
				result = (String) call.invoke(new Object[] {
						encode("12345678", userName.getBytes("GB18030")),
						encode("12345678", password.getBytes("GB18030")),
						encode("12345678", datasource.getBytes("GB18030")),
						encode("12345678", param.getBytes("GB18030")) });
				System.out.println("返回结果（解密前）:------------" + result);
			} catch (Exception e) {
				JSONUtils.printStr("");
				e.printStackTrace();
				return null;
			}
			String xmlDoc = "";
			try {
				xmlDoc = decodeValue("12345678", result);
				System.out.println("返回结果（解密后）:------------" + xmlDoc);

				System.out.println("返回结果（解密后）转UTF-8:------------"
						+ new String(xmlDoc.getBytes("UTF-8")));

			} catch (Exception e) {
				JSONUtils.printStr("");
				e.printStackTrace();
				return null;
			}
			String resultCode = "3";
			try {
				resultCode = xmlElements(xmlDoc);
				System.out.println("认证结果:------------" + resultCode);
			} catch (Exception e) {
				JSONUtils.printStr("");
				e.printStackTrace();
				return null;
			}
			
			if (resultCode.equals("3")) {// 认证成功
				// 修改认证标识
				Long r = userService.updateUserMater(userId);
				long result2 = userManageServic.updateUser(userId, realName,
						cardId);
				System.out.println("修改认证标识         " + r
						+ "     修改姓名  身份证 结果   ----------  " + result2);
				// 修改session参数
				user.setIsBindIdNo(1);
				user.setRealName(realName);
				session().setAttribute(IConstants.SESSION_USER, user);
				if (r > 0 && result2 > 0) {
					// 修改真实姓名、身份证号
					JSONUtils.printStr("3");
				} else {
					JSONUtils.printStr("");
				}

			} else if (resultCode.equals("2")) {// 认证失败（姓名身份证不一致）
				JSONUtils.printStr("2");
			} else if (resultCode.equals("1")) {// 认证失败（库中无此号）
				JSONUtils.printStr("1");
			} else {// 接口请求异常
				JSONUtils.printStr("");
			}
		}*/else{
			if(CertNoUtil.vId(cardId)){//认证成功
				// 修改认证标识
				Long r = userService.updateUserMater(userId);
				if(p.matcher(realName).find() || isSpecialChar(realName))	//判断姓名是否包含字母或特殊字符
				{
					JSONUtils.printStr("40004");//返回用户已经认证
				}
				long result2 = userManageServic.updateUser(userId, realName,cardId);
				// 修改session参数
				user.setIsBindIdNo(1);
				user.setRealName(realName);
				session().setAttribute(IConstants.SESSION_USER, user);
				if (r > 0 && result2 > 0) {
					// 修改真实姓名、身份证号
					JSONUtils.printStr("3");
				} else {
					JSONUtils.printStr("2");
				}
			}else{
				JSONUtils.printStr("2");
			}
		}
		
		return null;
	}
	
	public String xmlElements(String xmlDoc) throws JDOMException, IOException {
        StringReader read = new StringReader(xmlDoc);
        InputSource source = new InputSource(read);
        SAXBuilder sb = new SAXBuilder();
            Document doc = sb.build(source);
            Element root = doc.getRootElement();
            List jiedian = root.getChildren();
            Namespace ns = root.getNamespace();
            Element et = null;
            for(int i=0;i<jiedian.size();i++){
                et = (Element) jiedian.get(i);
            }
            et = (Element) jiedian.get(1);
            List zjiedian = et.getChildren();
            for(int j=0;j<zjiedian.size();j++){
                Element xet = (Element) zjiedian.get(j);
                if(xet.getName().equals("policeCheckInfo")){
                	 List jd = xet.getChildren();
                	 for(int k=0;k<jd.size();k++){
                         Element jd1 = (Element) jd.get(k);
                         System.out.println(jd1.getName());
                         System.out.println(jd1.getValue());
                         if(jd1.getName().equals("compStatus")){
                         	return  jd1.getValue();
                         }
                     }
                	return  xet.getValue();
                }
            }
        return "";
    }
	 
	 public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

	 
	    public static String encode(String key,String data) throws Exception
	    {
	        return encode(key, data.getBytes());
	    }

	    public static String encode(String key,byte[] data) throws Exception
	    {
	        try
	        {
		    	DESKeySpec dks = new DESKeySpec(key.getBytes());
		    	
		    	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	            Key secretKey = keyFactory.generateSecret(dks);
	            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
	            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
	            AlgorithmParameterSpec paramSpec = iv;
	            cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);
	            
	            byte[] bytes = cipher.doFinal(data);
	            return Base64.encode(bytes);
	        } catch (Exception e)
	        {
	            throw new Exception(e);
	        }
	    }


	    public static byte[] decode(String key,byte[] data) throws Exception
	    {
	        try
	        {
		    	DESKeySpec dks = new DESKeySpec(key.getBytes());
		    	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	            Key secretKey = keyFactory.generateSecret(dks);
	            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
	            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
	            AlgorithmParameterSpec paramSpec = iv;
	            cipher.init(Cipher.DECRYPT_MODE, secretKey,paramSpec);
	            return cipher.doFinal(data);
	        } catch (Exception e)
	        {
	            throw new Exception(e);
	        }
	    } 
	 
	    public static String decodeValue(String key,String data) throws Exception 
	    {
	    	byte[] datas;
	    	String value = null;
	    	
	    	datas = decode(key, Base64.decode(data));
			
			value = new String(datas);
			if (value.equals("")){
				throw new Exception();
			}
	    	return value;
	    }

	/**
	 * 判断是否含有特殊字符
	 *
	 * @param str
	 * @return true为包含，false为不包含
	 */
	public static boolean isSpecialChar(String str) {
		String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.find();
	}
	
	public RechargeService getRechargeService() {
		return rechargeService;
	}

	public void setRechargeService(RechargeService rechargeService) {
		this.rechargeService = rechargeService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public HomeInfoSettingService getHomeInfoSettingService() {
		return homeInfoSettingService;
	}

	public void setHomeInfoSettingService(
			HomeInfoSettingService homeInfoSettingService) {
		this.homeInfoSettingService = homeInfoSettingService;
	}

	public FinanceService getFinanceService() {
		return financeService;
	}

	public void setFinanceService(FinanceService financeService) {
		this.financeService = financeService;
	}

	public AdminService getAdminService() {
		return adminService;
	}

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public List<Map<String, Object>> getPotypeList() throws Exception {
		if (potypeList == null) {
			potypeList = rechargeService.queryTypeFund();
		}
		return potypeList;
	}

	public void setPotypeList(List<Map<String, Object>> potypeList) {
		this.potypeList = potypeList;
	}

	public List<Map<String, Object>> getBanksList() throws Exception {
		try {
			banksList = rechargebankService.queryrechargeBanklist();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return banksList;
	}

	public void setBanksList(List<Map<String, Object>> banksList) {
		this.banksList = banksList;
	}

	public RechargebankService getRechargebankService() {
		return rechargebankService;
	}

	public void setRechargebankService(RechargebankService rechargebankService) {
		this.rechargebankService = rechargebankService;
	}
	
	public UserManageServic getUserManageServic() {
		return userManageServic;
	}

	public void setUserManageServic(UserManageServic userManageServic) {
		this.userManageServic = userManageServic;
	}

}